﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using Newtonsoft.Json;

using CE.HotelEan;
using HotelWS;
using CE.Expedia;

public partial class travel_hotels_booking_manage : System.Web.UI.Page
{
    HotelWS.HotelServicesImplService hws = new HotelWS.HotelServicesImplService();

    private string _apikey = "98pndgasdzzxpugjzqpxw6za";
    private int _minorrev = 13;
    private Int64 _cid = 381988;
    private Int64 _hotelid = 0;
    private string _roomtypeid = "";
    private bool _isnonrefundable = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.Culture = "en-US";

        if (!Page.IsPostBack)
        {
            clearcontrols();

        }
    }

    protected void clearcontrols()
    {
        lblNoCharge.Visible = false;
        divRefund.Visible = false;

        lblItineraryNum.Text = "";
        lblBookingConfirmation.Text = "";
        lblHotelName.Text = "";
        lblHotelAddress.Text = "";
        lblPropertyDetails.Text = "";
        lblAmenities.Text = "";
        lblCheckin.Text = "";
        lblCheckout.Text = "";
        lblNights.Text = "";
        lblGuest.Text = "";
        lblGuests.Text = "";
        lblRoomType.Text = "";
        lblRooms.Text = "";
        lblRoomName.Text = "";
        lblRoomAmenities.Text = "";

        lblPriceDetails.Text = "";
        lblExtraPersonFee.Text = "";
        lblHotelTax.Text = "";
        lblSalesTax.Text = "";
        lblServiceFee.Text = "";
        lblPriceTax.Text = "";



    }

    protected void GetHotelInfo(Int64 hotelid, string roomtypeid)
    {
        HotelInformationRequest hotelreq = new HotelInformationRequest();
        hotelreq.apiKey = _apikey;
        hotelreq.cid = _cid;
        hotelreq.minorRev = _minorrev;
        hotelreq.minorRevSpecified = true;
        hotelreq.customerIpAddress = Request.UserHostAddress;
        hotelreq.customerUserAgent = Request.Browser.ToString();
        hotelreq.customerSessionId = "";
        hotelreq.currencyCode = "SGD";
        hotelreq.locale = LocaleType.en_US;
        hotelreq.localeSpecified = true;
        hotelreq.hotelId = hotelid;

        hotelInfoOption[] hotoption = new hotelInfoOption[5];
        hotoption[0] = hotelInfoOption.HOTEL_SUMMARY;
        hotoption[1] = hotelInfoOption.HOTEL_DETAILS;
        hotoption[2] = hotelInfoOption.ROOM_TYPES;
        hotoption[3] = hotelInfoOption.ROOM_AMENITIES;
        hotoption[4] = hotelInfoOption.PROPERTY_AMENITIES;

        string getData = "http://api.ean.com/ean-services/rs/hotel/v3/info?cid=" + hotelreq.cid
                + "&minorRev=26&apiKey=" + hotelreq.apiKey
                + "&locale=" + hotelreq.locale
                + "&currencyCode=" + hotelreq.currencyCode
                + "&customerIpAddress=" + hotelreq.customerIpAddress
                + "&customerUserAgent=" + hotelreq.customerUserAgent
                + "&_type=xml&customerSessionId=" + hotelreq.customerSessionId
                + "&xml="
                + "<HotelInformationRequest><hotelId>" + hotelreq.hotelId +
                "</hotelId>";

        getData += "</HotelInformationRequest>";

        CXHotelInfo hotelresp = new CXHotelInfo();

        // Handle JsonConvert array bug
        string returnJson = "";
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml(getXMLResult(getData));
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Suppliers"))
        {
            item.AppendChild(doc.CreateNode("element", "Supplier", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//roomAmenities"))
        {
            item.AppendChild(doc.CreateNode("element", "RoomAmenity", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//RoomTypes"))
        {
            item.AppendChild(doc.CreateNode("element", "RoomType", ""));
        }
        returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

        returnJson = returnJson.Replace("@", "");
        returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
        returnJson = returnJson.Replace("ns2:", "");
        hotelresp = JsonConvert.DeserializeObject<CXHotelInfo>(returnJson);

        //HotelInformationResponse hotelresp = new HotelInformationResponse();
        //hotelresp = hws.getInformation(hotelreq);

        if (hotelresp.HotelInformationResponse.HotelSummary != null && hotelresp.HotelInformationResponse.EanWsError == null)
        {
            inputLat.Value = hotelresp.HotelInformationResponse.HotelSummary.latitude.ToString();
            inputLong.Value = hotelresp.HotelInformationResponse.HotelSummary.longitude.ToString();

            if (hotelresp.HotelInformationResponse.PropertyAmenities != null)
            {
                lblAmenities.Text = "";

                foreach (CE.HotelEan.PropertyAmenity proprow in hotelresp.HotelInformationResponse.PropertyAmenities.PropertyAmenity)
                {
                    lblAmenities.Text += proprow.amenity + " * ";
                }
            }

            if (hotelresp.HotelInformationResponse.HotelDetails != null)
            {
                lblNotification.Text = System.Web.HttpUtility.HtmlDecode(hotelresp.HotelInformationResponse.HotelDetails.roomInformation);

                lblCheckin.Text = lblCheckin.Text + " " + hotelresp.HotelInformationResponse.HotelDetails.checkInTime;
                lblCheckout.Text = lblCheckout.Text + " " + hotelresp.HotelInformationResponse.HotelDetails.checkOutTime;
            }


            if (hotelresp.HotelInformationResponse.RoomTypes.RoomType != null)
            {
                foreach (CE.HotelEan.RoomType roomrow in hotelresp.HotelInformationResponse.RoomTypes.RoomType)
                {
                    if (roomrow.roomCode == roomtypeid)
                    {
                        if (roomrow.roomAmenities != null)
                        {
                            lblRoomAmenities.Text = "";

                            foreach (CE.HotelEan.RoomAmenity roomam in roomrow.roomAmenities.RoomAmenity)
                            {
                                lblRoomAmenities.Text += roomam.amenity + " * ";
                            }

                        }
                        break;
                    }
                }

            }

            inputLat.Value = hotelresp.HotelInformationResponse.HotelSummary.latitude.ToString();
            inputLong.Value = hotelresp.HotelInformationResponse.HotelSummary.longitude.ToString();

        }
        else
        {
            lblMessage.Text = hotelresp.HotelInformationResponse.EanWsError.presentationMessage;
        }
    }

    protected bool GetItinerary(string emailid, string itineraryid)
    {
        bool hasItinerary = false;
        ExpediaHotelBookingDB expdb = new ExpediaHotelBookingDB();
        DataTable dtBooking = new DataTable();
        dtBooking = expdb.GetBookingDetailsByEmailItinerary(emailid, itineraryid);

        if (dtBooking.Rows.Count > 0)
        {
            lblMessage.Text = "";
            string cancellationnum = "";
            if (dtBooking.Rows[0]["CancellationNumber"] != null)
            {
                cancellationnum = dtBooking.Rows[0]["CancellationNumber"].ToString();
            }

            int noOfRooms = int.Parse(dtBooking.Rows[0]["NoOfRooms"].ToString());

            HotelItineraryRequest reqdetails = new HotelItineraryRequest();
            reqdetails.apiKey = _apikey;
            reqdetails.cid = _cid;
            reqdetails.minorRev = _minorrev;
            reqdetails.minorRevSpecified = true;
            reqdetails.customerIpAddress = Request.UserHostAddress;
            reqdetails.customerSessionId = dtBooking.Rows[0]["CustomerSessionId"].ToString();
            reqdetails.customerUserAgent = Request.Browser.ToString();

            reqdetails.locale = LocaleType.en_US;
            reqdetails.localeSpecified = true;
            reqdetails.currencyCode = "SGD";
            reqdetails.itineraryId = int.Parse(itineraryid);
            reqdetails.itineraryIdSpecified = true;
            reqdetails.email = emailid;
            reqdetails.lastName = dtBooking.Rows[0]["LastName"].ToString();
            reqdetails.affiliateConfirmationId = dtBooking.Rows[0]["HotelBookingGUID"].ToString();
            reqdetails.affiliateCustomerId = dtBooking.Rows[0]["HotelBookingId"].ToString();

            inputbookingid.Value = reqdetails.affiliateCustomerId;
            //reqdetails.test = true;
            //reqdetails.testSpecified = true;
            string payathotel = "";
            string suppliertype = dtBooking.Rows[0]["SupplierType"].ToString();

            if (dtBooking.Rows[0]["info1"] != null)
            {
                payathotel = dtBooking.Rows[0]["info1"].ToString().Trim();
            }

            string getData = "http://api.ean.com/ean-services/rs/hotel/v3/itin?cid=" + reqdetails.cid
                + "&minorRev=26&apiKey=" + reqdetails.apiKey
                + "&locale=" + reqdetails.locale
                + "&currencyCode=" + reqdetails.currencyCode
                + "&customerIpAddress=" + reqdetails.customerIpAddress
                + "&customerUserAgent=" + reqdetails.customerUserAgent
                + "&_type=xml&customerSessionId=" + reqdetails.customerSessionId
                + "&xml="
                + "<HotelItineraryRequest><itineraryId>" + reqdetails.itineraryId +
                "</itineraryId><email>" + reqdetails.email +
                "</email><lastName>" + reqdetails.lastName +
                "</lastName><affiliateConfirmationId>" + reqdetails.affiliateConfirmationId +
                "</affiliateConfirmationId>";

            getData += "</HotelItineraryRequest>";

            CXHotelItinerary bookingdetails = new CXHotelItinerary();

            // Handle JsonConvert array bug
            string returnJson = "";
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(getXMLResult(getData));
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//Customer"))
            {
                item.AppendChild(doc.CreateNode("element", "CustomerAddresses", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//HotelConfirmation"))
            {
                item.AppendChild(doc.CreateNode("element", "ReservationGuest", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//HotelConfirmation"))
            {
                item.AppendChild(doc.CreateNode("element", "Hotel", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//Itinerary"))
            {
                item.AppendChild(doc.CreateNode("element", "HotelConfirmation", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//RateInfos"))
            {
                item.AppendChild(doc.CreateNode("element", "RateInfo", ""));
            }
            foreach (System.Xml.XmlNode item in doc.SelectNodes("//Surcharges"))
            {
                item.AppendChild(doc.CreateNode("element", "Surcharge", ""));
            }
            System.Xml.XmlElement root = doc.DocumentElement;
            root.AppendChild(doc.CreateNode("element", "Itinerary", ""));
            returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

            returnJson = returnJson.Replace("@", "");
            returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
            returnJson = returnJson.Replace("ns2:", "");
            bookingdetails = JsonConvert.DeserializeObject<CXHotelItinerary>(returnJson);

            //HotelItineraryResponse bookingdetails = new HotelItineraryResponse();
            //bookingdetails = hws.getItinerary(reqdetails);

            if (bookingdetails.HotelItineraryResponse.Itinerary != null && bookingdetails.HotelItineraryResponse.EanWsError == null)
            {
                hasItinerary = true;
                lblMessage.Text = "";
                divBookingDetails.Visible = true;
                lblPriceTax.Text = "";

                foreach (CE.HotelEan.Itinerary irow in bookingdetails.HotelItineraryResponse.Itinerary)
                {
                    lblItineraryNum.Text = irow.itineraryId.ToString();

                    lblBookingConfirmation.Text = "";
                    lblGuests.Text = "";
                    lblPriceDetails.Text = "";

                    int iconfirm = 1;
                    float totalcharge = 0;
                    float taxes = 0;
                    bool hasHotelTax = false;
                    bool hasSalesTax = false;
                    float hoteltax = 0;
                    float salestax = 0;
                    float extrapersonfee = 0;
                    float servicefee = 0;
                    int numberOfAdults = 0, numberOfChildren = 0;

                    foreach (CE.HotelEan.HotelConfirmation hconfirm in irow.HotelConfirmation)
                    {
                        string bookingstatus = "Confirmed"; //CF
                        _isnonrefundable = hconfirm.nonRefundable;

                        if (hconfirm.status == "CF")
                        {
                            bookingstatus = "Confirmed";
                            lblConfirm.Text = "Your reservation is confirmed.";
                            lblresmessage.Text = "*You will receive an email containing the confirmation and reservation details. "
                                    + "Please refer to your itinerary number if you contact customer service for any reason";

                            divPaymentInfo.Visible = true;
                            divRoomDetails.Visible = true;
                            divCharges.Visible = true;
                            divAddHotelInfo.Visible = true;
                            divTotalCharges.Visible = true;

                            divRefund.Visible = false;
                            divNonRefundable.Visible = false;

                        }
                        else if (hconfirm.status == "PS")
                        {
                            bookingstatus = "Pending";
                            lblConfirm.Text = "Your reservation is pending.";
                            lblresmessage.Text = "";

                            divPaymentInfo.Visible = true;
                            divRoomDetails.Visible = true;
                            divCharges.Visible = true;
                            divAddHotelInfo.Visible = true;
                            divTotalCharges.Visible = true;

                            divRefund.Visible = false;
                            divNonRefundable.Visible = false;

                        }
                        else if (hconfirm.status == "UC")
                        {
                            bookingstatus = "Unconfirmed";
                            lblConfirm.Text = "Your reservation is unconfirmed.";
                            lblresmessage.Text = "";

                            divPaymentInfo.Visible = true;
                            divRoomDetails.Visible = true;
                            divCharges.Visible = true;
                            divAddHotelInfo.Visible = true;
                            divTotalCharges.Visible = true;
                            divRefund.Visible = false;
                            divNonRefundable.Visible = false;
                        }
                        else if (hconfirm.status == "DT")
                        {
                            bookingstatus = "Deleted";
                            lblConfirm.Text = "Your reservation has been deleted.";
                            lblresmessage.Text = "";
                            divPaymentInfo.Visible = false;
                            divRoomDetails.Visible = false;
                            divCharges.Visible = false;
                            divAddHotelInfo.Visible = false;
                            divRefund.Visible = false;
                            divNonRefundable.Visible = false;
                            //divBookingDetails.Visible = false;
                            //lblMessage.Text = "";
                            //continue;
                            btnCancelReservation.Enabled = false;
                        }
                        else if (hconfirm.status == "CX")
                        {
                            bookingstatus = "Cancelled";
                            lblConfirm.Text = "Your reservation has been cancelled. <br/><br/> "
                                + "Your cancellation is confirmed, a cancellation email will be sent to your email address within 2 hours.";
                            lblresmessage.Text = "";
                            divPaymentInfo.Visible = false;
                            divRoomDetails.Visible = false;
                            divCharges.Visible = false;
                            divAddHotelInfo.Visible = false;

                            if (_isnonrefundable)
                            {
                                divNonRefundable.Visible = true;
                                divRefund.Visible = false;
                            }
                            else
                            {
                                divRefund.Visible = true;
                                divNonRefundable.Visible = false;
                            }
                            //divBookingDetails.Visible = false;
                            //lblMessage.Text = "";
                            //continue;
                        }
                        else if (hconfirm.status == "ER")
                        {
                            bookingstatus = "Error";
                            lblConfirm.Text = "Agent attention is needed for your reservation. Agent will follow up.";
                            lblresmessage.Text = "";

                            divPaymentInfo.Visible = true;
                            divRoomDetails.Visible = true;
                            divCharges.Visible = true;
                            divAddHotelInfo.Visible = true;
                            divTotalCharges.Visible = true;
                            divRefund.Visible = false;
                            divNonRefundable.Visible = false;
                            //divBookingDetails.Visible = false;
                            //lblMessage.Text = "";
                            //continue;
                        }


                        if (payathotel == "True" && suppliertype != "E")
                        {
                            if (hconfirm.status == "CX")
                            {
                                lblConfirm.Text = "Your reservation has been cancelled.<br/><br/> "
                                + "We have received your cancellation request and forwarded it to the property.";
                            }
                            else if (hconfirm.status == "CF")
                            {
                                lblConfirm.Text = "Your reservation is " + bookingstatus + ". Payment will be taken at the time of checkout by the hotel.";
                            }
                            else
                            {
                                lblConfirm.Text = "Your reservation is " + bookingstatus + ".";
                            }
                            lblNoCharge.Visible = true;
                        }
                        else
                        {
                            lblNoCharge.Visible = false; ;

                        }


                        lblBookingConfirmation.Text += "Room " + iconfirm.ToString() + " - "
                            + hconfirm.ReservationGuest[0].firstName + " " + hconfirm.ReservationGuest[0].lastName + " - "
                            + hconfirm.confirmationNumber.ToString() + " - " + bookingstatus
                            + "<br/>";

                        _hotelid = hconfirm.Hotel[0].hotelId;
                        _roomtypeid = hconfirm.roomType;

                        foreach (CE.HotelEan.Hotel hoteldetails in hconfirm.Hotel)
                        {
                            lblHotelName.Text = hoteldetails.name;
                            lblHotelAddress.Text = hoteldetails.address1 + " " + hoteldetails.address2
                                        + " " + hoteldetails.city + ", " + hoteldetails.countryCode;

                            string _hotelrating = hoteldetails.hotelRating.ToString();

                            if (_hotelrating == "0")
                            { btnStars.CssClass = "rating-0"; }
                            else if (_hotelrating == "1" || _hotelrating == "1.0")
                            { btnStars.CssClass = "rating-1"; }
                            else if (_hotelrating == "1.5")
                            { btnStars.CssClass = "rating-15"; }
                            else if (_hotelrating == "2" || _hotelrating == "2.0")
                            { btnStars.CssClass = "rating-2"; }
                            else if (_hotelrating == "2.5")
                            { btnStars.CssClass = "rating-25"; }
                            else if (_hotelrating == "3" || _hotelrating == "3.0")
                            { btnStars.CssClass = "rating-3"; }
                            else if (_hotelrating == "3.5")
                            { btnStars.CssClass = "rating-35"; }
                            else if (_hotelrating == "4" || _hotelrating == "4.0")
                            { btnStars.CssClass = "rating-4"; }
                            else if (_hotelrating == "4.5")
                            { btnStars.CssClass = "rating-45"; }
                            else if (_hotelrating == "5" || _hotelrating == "5.0")
                            { btnStars.CssClass = "rating-5"; }

                            lblPropertyDetails.Text = "";
                            lblAmenities.Text = "";
                        }

                        lblCheckin.Text = Convert.ToDateTime(hconfirm.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).ToString("MMM dd, yyyy");
                        lblCheckout.Text = Convert.ToDateTime(hconfirm.departureDate, System.Globalization.CultureInfo.InvariantCulture).ToString("MMM dd, yyyy");
                        lblNights.Text = hconfirm.nights.ToString();
                        numberOfAdults += hconfirm.numberOfAdults;
                        numberOfChildren += hconfirm.numberOfChildren;
                        lblGuest.Text = numberOfAdults.ToString() + " Adults ";

                        if (hconfirm.numberOfChildren > 0)
                        {
                            lblGuest.Text += numberOfChildren.ToString() + " Child";
                        }

                        lblRoomType.Text = hconfirm.roomDescription;
                        lblRoomName.Text = hconfirm.roomDescription;
                        lblRooms.Text = noOfRooms.ToString();

                        string currency = hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode;
                        float nightlyrate = 0;

                        if (suppliertype != "E")
                        {
                            divTotalCharges.Visible = false;
                            lblTaxDisclaimer.Text = "(Additional taxes and surcharges may be imposed by the hotel)";

                            lblPriceDisplayed.Text = "All prices are displayed in $ " + currency;

                            for (int i = 1; i <= noOfRooms; i++)
                            {
                                if (hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRate != null)
                                {
                                    string maxnightrate = string.Format("{0:0,0.00}", hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRate);
                                    lblPriceDetails.Text = "Room " + i.ToString() + " nightly rate* " + maxnightrate;
                                }
                            }

                        }
                        else
                        {
                            lblTaxDisclaimer.Text = "*Excluding tax recovery charges and service fees";
                        }

                        if (hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode == "SGD")
                        {
                            lblPriceDetails.Text += "Room " + iconfirm.ToString() + " <br/>";
                            int idays = 0;

                            if (hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom != null)
                            {
                                foreach (CE.HotelEan.NightlyRate nightrow in hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom.NightlyRate)
                                {
                                    //nightlyrate += nightrow.baseRate;
                                    string nightrate = string.Format("{0:0,0.00}", nightrow.rate);

                                    lblPriceDetails.Text += Convert.ToDateTime(hconfirm.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).AddDays(idays).ToString("dd MMM yyyy") + " " + hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode + " " +
                                            nightrate + "<br/>";

                                    idays++;
                                }
                            }
                            else if (hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRateSpecified)
                            {
                                lblPriceDetails.Text += Convert.ToDateTime(hconfirm.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).AddDays(idays).ToString("dd MMM yyyy") + " " + hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode + " " +
                                                                                   hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRate + "<br/>";
                            }

                            if (hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.total <= 0)
                            {
                                totalcharge += hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.nightlyRateTotal;
                                lblTotalCharge.Text = currency + " " + string.Format("{0:0,0.00}", totalcharge);
                            }
                            else
                            {
                                totalcharge += hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.total;
                                lblTotalCharge.Text = currency + " " + string.Format("{0:0,0.00}", totalcharge);
                            }

                            if (hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges != null)
                            {

                                foreach (CE.HotelEan.Surcharge srow in hconfirm.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges.Surcharge)
                                {
                                    if (srow.type == CE.HotelEan.SurchargeType.ExtraPersonFee)
                                    {
                                        extrapersonfee += srow.amount;
                                    }

                                    if (srow.type == CE.HotelEan.SurchargeType.SalesTax)
                                    {
                                        hasSalesTax = true;
                                        salestax += srow.amount;
                                    }

                                    if (srow.type == CE.HotelEan.SurchargeType.HotelOccupancyTax)
                                    {
                                        hasHotelTax = true;
                                        hoteltax += srow.amount;
                                    }

                                    if (srow.type == CE.HotelEan.SurchargeType.ServiceFee)
                                    {
                                        servicefee += srow.amount;
                                    }

                                    if (srow.type == CE.HotelEan.SurchargeType.TaxAndServiceFee)
                                    {
                                        taxes += srow.amount;
                                    }

                                }

                                if (extrapersonfee > 0)
                                {
                                    lblExtraPersonFee.Text = "Extra person fees" + " " + currency + " " + string.Format("{0:0,0.00}", extrapersonfee) + "<br/>";
                                }

                                if (servicefee > 0)
                                {
                                    lblServiceFee.Text = "Sevice Fee" + " " + currency + " " + string.Format("{0:0,0.00}", extrapersonfee) + "<br/>";
                                }

                                if (hasHotelTax && hasSalesTax)
                                {
                                    lblHotelTax.Text = "Hotel Occupancy and Sales Tax " + " " + currency + " " + (string.Format("{0:0,0.00}", hoteltax + salestax)) + "<br/>";
                                }
                                else
                                {
                                    if (hasHotelTax)
                                    {
                                        lblHotelTax.Text = "Hotel Occupancy Tax " + " " + currency + " " + (string.Format("{0:0,0.00}", hoteltax)) + "<br/>";
                                    }
                                    if (hasSalesTax)
                                    {
                                        lblSalesTax.Text += "Sales Tax " + " " + currency + " " + (string.Format("{0:0,0.00}", salestax)) + "<br/>";
                                    }
                                }

                                if (taxes > 0)
                                {
                                    lblPriceTax.Text = "Tax Recovery Charges and Service Fees " + currency + " " + string.Format("{0:0,0.00}", taxes) + "<br/>";

                                }

                            }
                        }
                        else   //converted
                        {
                            if (hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo != null)
                            {
                                currency = hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode;

                                lblPriceDetails.Text += "Room " + iconfirm.ToString() + " <br/>";
                                int idays = 0;

                                if (hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom != null)
                                {
                                    foreach (CE.HotelEan.NightlyRate nightrow in hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom.NightlyRate)
                                    {
                                        //nightlyrate += nightrow.baseRate;
                                        string nightrate = string.Format("{0:0,0.00}", nightrow.rate);

                                        lblPriceDetails.Text += Convert.ToDateTime(hconfirm.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).AddDays(idays).ToString("dd MMM yyyy") + " " + hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode + " " +
                                                nightrate + "<br/>";

                                        idays++;
                                    }
                                }
                                else if (hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRateSpecified)
                                {
                                    lblPriceDetails.Text += Convert.ToDateTime(hconfirm.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).AddDays(idays).ToString("dd MMM yyyy") + " " + hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode + " " +
                                                                                       hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRate + "<br/>";
                                }

                                if (hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.total <= 0)
                                {
                                    totalcharge += hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.nightlyRateTotal;
                                    lblTotalCharge.Text = currency + " " + string.Format("{0:0,0.00}", totalcharge);
                                }
                                else
                                {
                                    totalcharge += hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.total;
                                    lblTotalCharge.Text = currency + " " + string.Format("{0:0,0.00}", totalcharge);
                                }

                                if (hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.Surcharges != null)
                                {

                                    foreach (CE.HotelEan.Surcharge srow in hconfirm.RateInfos.RateInfo[0].ConvertedRateInfo.Surcharges.Surcharge)
                                    {
                                        if (srow.type == CE.HotelEan.SurchargeType.ExtraPersonFee)
                                        {
                                            extrapersonfee += srow.amount;
                                        }

                                        if (srow.type == CE.HotelEan.SurchargeType.SalesTax)
                                        {
                                            hasSalesTax = true;
                                            salestax += srow.amount;
                                        }

                                        if (srow.type == CE.HotelEan.SurchargeType.HotelOccupancyTax)
                                        {
                                            hasHotelTax = true;
                                            hoteltax += srow.amount;
                                        }

                                        if (srow.type == CE.HotelEan.SurchargeType.ServiceFee)
                                        {
                                            servicefee += srow.amount;
                                        }

                                        if (srow.type == CE.HotelEan.SurchargeType.TaxAndServiceFee)
                                        {
                                            taxes += srow.amount;
                                        }

                                    }

                                    if (extrapersonfee > 0)
                                    {
                                        lblExtraPersonFee.Text = "Extra person fees" + " " + currency + " " + string.Format("{0:0,0.00}", extrapersonfee) + "<br/>";
                                    }

                                    if (servicefee > 0)
                                    {
                                        lblServiceFee.Text = "Sevice Fee" + " " + currency + " " + string.Format("{0:0,0.00}", extrapersonfee) + "<br/>";
                                    }

                                    if (hasHotelTax && hasSalesTax)
                                    {
                                        lblHotelTax.Text = "Hotel Occupancy and Sales Tax " + " " + currency + " " + (string.Format("{0:0,0.00}", hoteltax + salestax)) + "<br/>";
                                    }
                                    else
                                    {
                                        if (hasHotelTax)
                                        {
                                            lblHotelTax.Text = "Hotel Occupancy Tax " + " " + currency + " " + (string.Format("{0:0,0.00}", hoteltax)) + "<br/>";
                                        }
                                        if (hasSalesTax)
                                        {
                                            lblSalesTax.Text += "Sales Tax " + " " + currency + " " + (string.Format("{0:0,0.00}", salestax)) + "<br/>";
                                        }
                                    }

                                    if (taxes > 0)
                                    {
                                        lblPriceTax.Text = "Tax Recovery Charges and Service Fees " + currency + " " + string.Format("{0:0,0.00}", taxes) + "<br/>";

                                    }
                                }
                            }
                        }

                        if (hconfirm.ReservationGuest != null)
                        {
                            lblGuests.Text += "Room " + iconfirm.ToString() + "<br/>";

                            if (hconfirm.numberOfChildren > 0)
                            {
                                lblGuests.Text += "Guests: " + hconfirm.ReservationGuest[0].firstName + " " + hconfirm.ReservationGuest[0].lastName + ", " + hconfirm.numberOfAdults.ToString() + " Adults";
                                lblGuests.Text += " , " + hconfirm.numberOfChildren.ToString() + " Child <br/>";
                            }
                            else
                            {
                                lblGuests.Text += "Guests: " + hconfirm.ReservationGuest[0].firstName + " " + hconfirm.ReservationGuest[0].lastName + ", " + hconfirm.numberOfAdults.ToString() + " Adults <br/>";
                            }
                        }

                        lblCancellation.Text = hconfirm.cancellationPolicy;

                        iconfirm++;
                    }

                    lblCardholder.Text = irow.Customer.firstName + " " + irow.Customer.lastName;
                    lblBillingAddress.Text = irow.Customer.CustomerAddresses[0].address1;

                    if (irow.Customer.CustomerAddresses[0].address2 != "")
                    {
                        lblBillingAddress.Text += " " + irow.Customer.CustomerAddresses[0].address2;
                    }

                    lblBillingAddress.Text += ", " + irow.Customer.CustomerAddresses[0].city;

                    if (irow.Customer.CustomerAddresses[0].stateProvinceCode != "")
                    {
                        lblBillingAddress.Text += " " + irow.Customer.CustomerAddresses[0].stateProvinceCode;
                    }

                    lblBillingAddress.Text += ", " + irow.Customer.CustomerAddresses[0].countryCode;
                    lblBillingAddress.Text += ", " + irow.Customer.CustomerAddresses[0].postalCode;

                    lblEmailAddress.Text = irow.Customer.email;
                    lblPhone.Text = irow.Customer.homePhone;
                }
            }
            else
            {
                lblMessage.Text = bookingdetails.HotelItineraryResponse.EanWsError.presentationMessage; // +" <br/>" + bookingdetails.HotelItineraryResponse.EanWsError.verboseMessage;
                lblConfirm.Visible = false;

                divBookingDetails.Visible = false;
            }
        }
        else
        {
            divBookingDetails.Visible = false;
            lblMessage.Text = "This email address does not match the email on this itinerary.";
        }

        return hasItinerary;

    }

    protected void btnViewReservation_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (GetItinerary(txtEmailAddress.Text, txtItinerary.Text))
            {
                GetHotelInfo(_hotelid, _roomtypeid);
            }
        }
    }

    protected void btnCancelReservation_Click(object sender, EventArgs e)
    {
        HotelRoomCancellationRequest cancelreq = new HotelRoomCancellationRequest();

        cancelreq.apiKey = _apikey;
        cancelreq.cid = _cid;
        cancelreq.minorRev = _minorrev;
        cancelreq.customerIpAddress = Request.UserHostAddress;
        cancelreq.customerSessionId = ""; // dtBooking.Rows[0]["CustomerSessionId"].ToString();
        cancelreq.customerUserAgent = Request.Browser.ToString();
        cancelreq.locale = LocaleType.en_US;
        cancelreq.currencyCode = "SGD";
        cancelreq.itineraryId = int.Parse(lblItineraryNum.Text.Trim());
        cancelreq.email = txtEmailAddress.Text;
        cancelreq.confirmationNumber = lblConfirm.Text.Trim();
        cancelreq.reason = "COP";

        string getData = "http://api.ean.com/ean-services/rs/hotel/v3/cancel?cid=" + cancelreq.cid
                + "&minorRev=26&apiKey=" + cancelreq.apiKey
                + "&locale=" + cancelreq.locale
                + "&currencyCode=" + cancelreq.currencyCode
                + "&customerIpAddress=" + cancelreq.customerIpAddress
                + "&customerUserAgent=" + cancelreq.customerUserAgent
                + "&_type=xml&customerSessionId=" + cancelreq.customerSessionId
                + "&xml="
                + "<HotelRoomCancellationRequest><itineraryId>" + cancelreq.itineraryId +
                "</itineraryId><email>" + cancelreq.email +
                "</email><confirmationNumber>" + cancelreq.confirmationNumber +
                "</confirmationNumber><reason>" + cancelreq.reason +
                "</reason>";

        getData += "</HotelRoomCancellationRequest>";

        CXHotelRoomCancellation cancelresp = new CXHotelRoomCancellation();

        // Handle JsonConvert array bug
        string returnJson = "";
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml(getXMLResult(getData));
        returnJson = JsonConvert.SerializeXmlNode(doc);
        returnJson = returnJson.Replace("@", "");
        returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
        returnJson = returnJson.Replace("ns2:", "");
        cancelresp = JsonConvert.DeserializeObject<CXHotelRoomCancellation>(returnJson);

        //HotelRoomCancellationResponse cancelresp = new HotelRoomCancellationResponse();
        //cancelresp = hws.getCancellation(cancelreq);

        if (cancelresp != null && cancelresp.HotelRoomCancellationResponse.EanWsError == null)
        {
            if (cancelresp.HotelRoomCancellationResponse.cancellationNumber != "" && cancelresp.HotelRoomCancellationResponse.customerSessionId != "")
            {
                if (inputbookingid.Value != "")
                {
                    ExpediaHotelBookingDB expdb = new ExpediaHotelBookingDB();
                    expdb.CancelBooking(int.Parse(inputbookingid.Value), cancelresp.HotelRoomCancellationResponse.cancellationNumber.ToString());
                }

                lblMessage.Text = "Your booking has been cancelled.";

                divBookingDetails.Visible = false;
            }
            else
            {
                lblMessage.Text = "Something went wrong. Pls. try cancelling again.";
            }
        }
        else
        {
            //lblMessage.Text = "Something went wrong. Pls. try cancelling again.";

            lblMessage.Text = cancelresp.HotelRoomCancellationResponse.EanWsError.presentationMessage; // +"<br/> " + cancelresp.EanWsError.verboseMessage; 
        }

    }
    private string getXMLResult(string requestData)
    {
        WebRequest request = null;
        request = WebRequest.Create(requestData);
        request.Method = "GET";
        WebResponse response = request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        responseFromServer = responseFromServer.Replace("@", "");
        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;
    }
}
